﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using XiAnAirport.BUS.RocketMQ;
using XiAnAirport.DAL;
using XiAnAirport.ElevatorWebSocket;
using XiAnAirport.Models;

namespace XiAnAirport.BUS
{
    public class MqttDataBUS
    {
        public void MqttDataProcess(DeviceStatusTotal deviceStatusTotal, string topic, string manufacturerId)
        {
            try
            {
                MqttDataDAL mqttDataDAL = new MqttDataDAL();

                mqttdata mqttdata = new mqttdata();
                mqttdata.manufacturerId = manufacturerId;
                mqttdata.manufacturer = GetManufacturer(manufacturerId);
                mqttdata.topicType = topic;
                string type = string.Empty;
                for (int i = 0; i < 5; i++)
                {
                    if (i == 0)
                    {
                        mqttdata.dataNum = deviceStatusTotal.normalTotal;
                        type = "normalTotal";
                    }
                    else if (i == 1)
                    {
                        mqttdata.dataNum = deviceStatusTotal.faultTotal;
                        type = "faultTotal";
                    }
                    else if (i == 2)
                    {
                        mqttdata.dataNum = deviceStatusTotal.maintenanceTotal;
                        type = "maintenanceTotal";
                    }
                    else if (i == 3)
                    {
                        mqttdata.dataNum = deviceStatusTotal.offlineTotal;
                        type = "offlineTotal";
                    }
                    else if (i == 4)
                    {
                        mqttdata.dataNum = deviceStatusTotal.deviceTotal;
                        type = "deviceTotal";
                    }
                    mqttdata.dataType = type;
                    bool result = mqttDataDAL.CheckData(mqttdata.manufacturer, manufacturerId, type, topic);
                    if (result)
                    {
                        mqttDataDAL.UpdateMqttData(mqttdata);
                    }
                    else
                    {
                        mqttDataDAL.AddMqttData(mqttdata);
                    }
                    bool result_5 = PushNoticeMessage("Refresh").Result;
                }
            }
            catch (Exception e)
            {
                LogBUS logBUS = new LogBUS();
                ErrorLogInfo errorLogInfo = new ErrorLogInfo();
                errorLogInfo.operation = "初始化第三方设备状态";
                errorLogInfo.errorMsg = e.ToString();
                logBUS.InsertErrorLog(errorLogInfo);
                LogHelper.Log("初始化第三方设备状态" + e.ToString());
            }
        }

        public void MqttDataProcess(TodayProcess todayProcess, string topic, string manufacturerId)
        {
            try
            {
                MqttDataDAL mqttDataDAL = new MqttDataDAL();

                for (int i = 0; i < 6; i++)
                {
                    mqttdata mqttdata = new mqttdata();
                    mqttdata.manufacturerId = manufacturerId;
                    mqttdata.manufacturer = GetManufacturer(manufacturerId);
                    mqttdata.topicType = topic;
                    string type = string.Empty;
                    if (i == 0)
                    {
                        mqttdata.dataNum = todayProcess.inspectionTotal;
                        type = "inspectionTotal";
                    }
                    else if (i == 1)
                    {
                        mqttdata.dataNum = todayProcess.maintenanceTotal;
                        type = "maintenanceTotal";
                    }
                    else if (i == 2)
                    {
                        mqttdata.dataNum = todayProcess.faultTotal;
                        type = "faultTotal";
                    }
                    else if (i == 3)
                    {
                        mqttdata.dataNum = todayProcess.inspectionCompleted;
                        type = "inspectionCompleted";
                    }
                    else if (i == 4)
                    {
                        mqttdata.dataNum = todayProcess.maintenanceCompleted;
                        type = "maintenanceCompleted";
                    }
                    else if (i == 5)
                    {
                        mqttdata.dataNum = todayProcess.faultCompleted;
                        type = "faultCompleted";
                    }
                    bool result = mqttDataDAL.CheckData(mqttdata.manufacturer, manufacturerId, type, topic);
                    mqttdata.dataType = type;
                    if (result)
                    {
                        mqttDataDAL.UpdateMqttData(mqttdata);
                    }
                    else
                    {
                        mqttDataDAL.AddMqttData(mqttdata);
                    }
                    bool result_5 = PushNoticeMessage("Refresh").Result;
                }
            }
            catch (Exception e)
            {
                LogBUS logBUS = new LogBUS();
                ErrorLogInfo errorLogInfo = new ErrorLogInfo();
                errorLogInfo.operation = "初始化今日待办";
                errorLogInfo.errorMsg = e.ToString();
                logBUS.InsertErrorLog(errorLogInfo);
                LogHelper.Log("初始化今日待办" + e.ToString());
            }
        }

        public void MqttDataProcess(string manufacturerId, string type, string topic, double dataNum)
        {
            try
            {
                MqttDataDAL mqttDataDAL = new MqttDataDAL();
                mqttdata mqttdata = new mqttdata();
                mqttdata.manufacturerId = manufacturerId;
                mqttdata.manufacturer = GetManufacturer(manufacturerId);
                mqttdata.topicType = topic;
                mqttdata.dataType = type;
                mqttdata.dataNum = dataNum;
                bool result = mqttDataDAL.CheckData(mqttdata.manufacturer, manufacturerId, type, topic);
                if (result)
                {
                    mqttDataDAL.UpdateMqttData(mqttdata);
                }
                else
                {
                    mqttDataDAL.AddMqttData(mqttdata);
                }
                bool result_5 = PushNoticeMessage("Refresh").Result;
            }
            catch (Exception e)
            {
                LogBUS logBUS = new LogBUS();
                ErrorLogInfo errorLogInfo = new ErrorLogInfo();
                errorLogInfo.operation = "初始化今日运行时长";
                errorLogInfo.errorMsg = e.ToString();
                logBUS.InsertErrorLog(errorLogInfo);
                LogHelper.Log("初始化今日运行时长" + e.ToString());
            }
        }

        public void MqttFaultStatistics(string manufacturerId, string topic, int faultTotal, int faultToday)
        {
            try
            {
                MqttDataDAL mqttDataDAL = new MqttDataDAL();
                for (int i = 0; i < 2; i++)
                {
                    mqttdata mqttdata = new mqttdata();
                    mqttdata.manufacturerId = manufacturerId;
                    mqttdata.manufacturer = GetManufacturer(manufacturerId);
                    mqttdata.topicType = topic;
                    if (i == 0)
                    {
                        mqttdata.dataType = "faultTotal";
                        mqttdata.dataNum = faultTotal;
                    }
                    else
                    {
                        mqttdata.dataType = "faultToday";
                        mqttdata.dataNum = faultToday;
                    }
                    bool result = mqttDataDAL.CheckData(mqttdata.manufacturer, manufacturerId, mqttdata.dataType, topic);
                    if (result)
                    {
                        mqttDataDAL.UpdateMqttData(mqttdata);
                    }
                    else
                    {
                        mqttDataDAL.AddMqttData(mqttdata);
                    }
                    bool result_5 = PushNoticeMessage("Refresh").Result;
                }
            }
            catch (Exception e)
            {
                LogBUS logBUS = new LogBUS();
                ErrorLogInfo errorLogInfo = new ErrorLogInfo();
                errorLogInfo.operation = "初始化故障次数";
                errorLogInfo.errorMsg = e.ToString();
                logBUS.InsertErrorLog(errorLogInfo);
                LogHelper.Log("初始化故障次数" + e.ToString());
            }

        }

        public void MqttFaultRecordDataProcess(FaultRecordReport faultRecordReport)
        {
            int id = 0;
            try
            {
                MqttDataDAL mqttDataDAL = new MqttDataDAL();
                mqttDataDAL.AddFaultRecordData(faultRecordReport);
            }
            catch (Exception e)
            {
                LogBUS logBUS = new LogBUS();
                ErrorLogInfo errorLogInfo = new ErrorLogInfo();
                errorLogInfo.operation = "故障上报";
                errorLogInfo.errorMsg = e.ToString();
                logBUS.InsertErrorLog(errorLogInfo);
                LogHelper.Log("故障上报" + e.ToString());
            }
        }

        public async void KoneFaultRecord(KoneFaultReport koneFaultReport)
        {
            try
            {
                int faultrecoreid;
                FaultRecordReport faultRecordReport = new FaultRecordReport();
                FaultReportInfo faultReportInfo = new FaultReportInfo();
                ElevatorAreaDAL elevatorAreaDAL = new ElevatorAreaDAL();
                Elevator elevator = elevatorAreaDAL.QueryElevatorByOpc(koneFaultReport.opcNO);
                if (elevator != null)
                {

                    RepairWorkOrderDAL repairWorkOrderDAL = new RepairWorkOrderDAL();
                    AddRepairOrder(koneFaultReport, elevator.id, out faultrecoreid);

                    //大屏今日故障记录
                    faultRecordReport.elevatorName = elevator.elevatorName;
                    faultRecordReport.elevatorNo = elevator.elevatorName;
                    faultRecordReport.areaName = elevator.areaName;
                    faultRecordReport.elevatorType = elevator.elevatorType;
                    faultRecordReport.updateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    faultRecordReport.manufacturer = "KONE";
                    faultRecordReport.internalNo = koneFaultReport.opcNO;
                    faultRecordReport.faultType = koneFaultReport.Fault_Type;
                    faultRecordReport.faultContent = koneFaultReport.Fault_Cause;
                    faultRecordReport.faultTime = Convert.ToDateTime(koneFaultReport.Reporttime).ToString("yyyy-MM-dd HH:mm:ss");
                    MqttFaultRecordDataProcess(faultRecordReport);

                    //故障推送
                    ElevatorFault elevatorFault = new ElevatorFault();
                    elevatorFault.elevatorName = elevator.elevatorName;
                    elevatorFault.elevatorNO = elevator.elevatorNO;
                    elevatorFault.areaName = elevator.areaName;
                    elevatorFault.mainAreaName = elevator.mainAreaName;
                    elevatorFault.Fault_Cause = koneFaultReport.Fault_Cause;
                    elevatorFault.cameraNo = elevator.cameraNo;
                    elevatorFault.FaultTime = Convert.ToDateTime(koneFaultReport.Reporttime).ToString("yyyy-MM-dd HH:mm:ss");
                    InitWorkOrder();
                    bool result2 = PushFaultReportMessage(elevatorFault).Result;
                    bool result3 = PushPromptMessage("PromptRefresh").Result;

                   

                    ElevatorStateBUS elevatorStateBUS = new ElevatorStateBUS();
                    LiftStateALL liftStateALL = elevatorStateBUS.GetElevatorState(elevator.opcNO, elevator.id);
                    //bool send_result = elevatorStateBUS.PushElevatorSingleMessage(elevator.id, liftStateALL).Result;
                }
            }
            catch (Exception e)
            {
                LogBUS logBUS = new LogBUS();
                ErrorLogInfo errorLogInfo = new ErrorLogInfo();
                errorLogInfo.operation = "通力故障上报";
                errorLogInfo.errorMsg = e.ToString();
                logBUS.InsertErrorLog(errorLogInfo);
                LogHelper.Log("通力故障上报" + e.ToString());
            }
        }

        public string GenerateRandomString(int length)
        {
            string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
            Random random = new Random();
            return new string(Enumerable.Repeat(chars, length)
              .Select(s => s[random.Next(s.Length)]).ToArray());
        }

        public void DistinctData()
        {
            MqttDataDAL mqttDataDAL = new MqttDataDAL();
            mqttDataDAL.DeleteDistinctFaultReport();
            mqttDataDAL.DeleteDistinctMqttFaultrecord();
            mqttDataDAL.DeleteDistinctRepairWorkorder();

            //大屏今日故障统计
            bool result = mqttDataDAL.CheckData("KONE", "04", "faultTotal", "FaultStatistics");
            RepairWorkOrderDAL repairWorkOrderDAL1 = new RepairWorkOrderDAL();
            mqttdata mqttdata = new mqttdata();
            mqttdata.dataType = "faultTotal";
            mqttdata.manufacturer = "KONE";
            mqttdata.manufacturerId = "04";
            mqttdata.topicType = "FaultStatistics";
            mqttdata.dataNum = repairWorkOrderDAL1.QueryAllFaultReportCount();
            if (result)
            {
                mqttDataDAL.UpdateMqttData(mqttdata);
            }
            else
            {
                mqttDataDAL.AddMqttData(mqttdata);
            }

            //系统首页今日故障
            bool result1 = mqttDataDAL.CheckData("KONE", "04", "faultToday", "FaultStatistics");
            mqttdata mqttdata1 = new mqttdata();
            mqttdata1.dataType = "faultToday";
            mqttdata1.manufacturer = "KONE";
            mqttdata1.manufacturerId = "04";
            mqttdata1.topicType = "FaultStatistics";
            mqttdata1.dataNum = repairWorkOrderDAL1.QueryFaultReportCount();
            if (result1)
            {
                mqttDataDAL.UpdateMqttData(mqttdata1);
            }
            else
            {
                mqttDataDAL.AddMqttData(mqttdata1);
            }
            //工单初始化
            InitWorkOrder();
            bool result3 = PushPromptMessage("PromptRefresh").Result;
        }

        public void SlaveKoneFaultRecord(KoneFaultReport koneFaultReport)
        {
            try
            {
                FaultRecordReport faultRecordReport = new FaultRecordReport();
                FaultReportInfo faultReportInfo = new FaultReportInfo();
                ElevatorAreaDAL elevatorAreaDAL = new ElevatorAreaDAL();
                Elevator elevator = elevatorAreaDAL.QueryElevatorByOpc(koneFaultReport.opcNO);
                if (elevator != null)
                {
                    //故障推送
                    ElevatorFault elevatorFault = new ElevatorFault();
                    elevatorFault.elevatorName = elevator.elevatorName;
                    elevatorFault.elevatorNO = elevator.elevatorNO;
                    elevatorFault.areaName = elevator.areaName;
                    elevatorFault.mainAreaName = elevator.mainAreaName;
                    elevatorFault.Fault_Cause = koneFaultReport.Fault_Cause;
                    elevatorFault.cameraNo = elevator.cameraNo;
                    elevatorFault.FaultTime = Convert.ToDateTime(koneFaultReport.Reporttime).ToString("yyyy-MM-dd HH:mm:ss");
                    InitWorkOrder();
                    bool result2 = PushFaultReportMessage(elevatorFault).Result;
                    bool result3 = PushPromptMessage("PromptRefresh").Result;

                    ElevatorStateBUS elevatorStateBUS = new ElevatorStateBUS();
                    LiftStateALL liftStateALL = elevatorStateBUS.GetElevatorState(elevator.opcNO, elevator.id);
                    // bool send_result = elevatorStateBUS.PushElevatorSingleMessage(elevator.id, liftStateALL).Result;
                }
            }
            catch (Exception e)
            {
                LogBUS logBUS = new LogBUS();
                ErrorLogInfo errorLogInfo = new ErrorLogInfo();
                errorLogInfo.operation = "通力故障上报";
                errorLogInfo.errorMsg = e.ToString();
                logBUS.InsertErrorLog(errorLogInfo);
                LogHelper.Log("通力故障上报" + e.ToString());
            }
        }

        public void AddRepairOrder(KoneFaultReport koneFaultReport, int elevatorid, out int faultid)
        {
            faultid = 0;

            try
            {
                FaultReportInfo faultReportInfo = new FaultReportInfo();
                RepairWorkOrderDAL repairWorkOrderDAL = new RepairWorkOrderDAL();
                //RepairWorkOrderBUS repairWorkOrderBUS = new RepairWorkOrderBUS();
                //string orderno = repairWorkOrderBUS.GetWorkNo();
                MqttDataDAL mqttDataDAL = new MqttDataDAL();
                mqttDataDAL.DeleteDistinctRepairWorkorder();
                //int orderid = repairWorkOrderDAL.InsertWorkOrder(koneFaultReport, elevatorid, orderno);
                // if (orderid > 0)
                //{
                faultReportInfo.elevatorID = elevatorid;
                faultReportInfo.faultTime = Convert.ToDateTime(koneFaultReport.Reporttime).ToString("yyyy-MM-dd HH:mm:ss");
                faultReportInfo.faultCode = koneFaultReport.Fault_Cause;
                faultReportInfo.faultSource = "设备上报";
                //faultReportInfo.orderId = orderid;
                repairWorkOrderDAL.AddFaultReport(faultReportInfo, out faultid);
                //}

            }
            catch
            {

            }
        }

        public string GetManufacturer(string id)
        {
            switch (id)
            {
                case "04": return "KONE";
                case "01": return "Schindler";
                case "02": return "TKE";
                case "03": return "TOSHIBA";
                default: return "";
            }
        }

        public async Task<bool> PushFaultReportMessage(ElevatorFault elevatorFault)
        {
            return await ElevatorWebSocketMiddleware.webSocketManage.PushFaultReportMessage(elevatorFault);
        }

        public static async Task<bool> PushNoticeMessage(string message)
        {
            try
            {
                if (ElevatorWebSocketMiddleware.webSocketManage == null)
                {
                    return false;
                }
                else
                {
                    return await ElevatorWebSocketMiddleware.webSocketManage.PushNoticeMessage(message);
                }
            }
            catch
            {
                return false;
            }
        }

        public static void InitWorkOrder()
        {
            try
            {
                MqttDataDAL mqttDataDAL = new MqttDataDAL();
                int inspection = 0;
                for (int i = 0; i < 2; i++)
                {
                    try
                    {
                        string type = string.Empty;
                        int datanum = 0;

                        mqttdata mqttdata = new mqttdata();

                        if (i == 0)
                        {
                            type = "faultTotal";
                            List<mqttdata> list = mqttDataDAL.QueryMqttdata("OrderIncomplete", "04", "KONE");
                            int old_value = (int)list.FirstOrDefault(x => x.dataType == "repair").dataNum;
                            datanum = old_value + mqttDataDAL.QueryInCompletelRepairOrder();
                            inspection = datanum;
                        }
                        else if (i == 1)
                        {
                            type = "faultCompleted";
                            datanum = inspection - mqttDataDAL.QueryAllInCompletelRepairOrder();
                        }

                        mqttdata.dataNum = datanum;
                        mqttdata.manufacturer = "KONE";
                        mqttdata.manufacturerId = "04";
                        mqttdata.topicType = "TodayProcess";
                        mqttdata.dataType = type;
                        bool result = mqttDataDAL.CheckData(mqttdata.manufacturer, mqttdata.manufacturerId, type, mqttdata.topicType);

                        if (result)
                        {
                            mqttDataDAL.UpdateMqttData(mqttdata);
                        }
                        else
                        {
                            mqttDataDAL.AddMqttData(mqttdata);
                        }
                    }
                    catch
                    {
                        continue;
                    }
                }
                bool result_5 = PushNoticeMessage("Refresh").Result;
                bool result_6 = PushKoneHomeMessage("RefreshHomePage").Result;
            }
            catch (Exception e)
            {
                LogBUS logBUS = new LogBUS();
                ErrorLogInfo errorLogInfo = new ErrorLogInfo();
                errorLogInfo.operation = "初始化工单数量";
                errorLogInfo.errorMsg = e.ToString();
                logBUS.InsertErrorLog(errorLogInfo);
                LogHelper.Log("初始化工单数量" + e.ToString());
            }
        }

        public static async Task<bool> PushKoneHomeMessage(string message)
        {
            return await ElevatorWebSocketMiddleware.webSocketManage.PushKoneHomeMessage(message);
        }

        public static async Task<bool> PushPromptMessage(string message)
        {
            return await ElevatorWebSocketMiddleware.webSocketManage.PushPromptMessage(message);
        }
    }
}
